package com.ysmygx.service.impl;

import cn.hutool.core.util.XmlUtil;
import cn.hutool.http.Header;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import com.alibaba.fastjson2.JSON;
import com.ysmygx.entity.RequestBody;
import com.ysmygx.service.SignService;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.w3c.dom.Document;

import javax.xml.xpath.XPathConstants;

@Log4j2
@Service
public class SignServiceImpl implements SignService {
    @Value("${pay.sign-url}")
    private String url;
    private final String contentType = "INFOSEC_SIGN/1.0";
    @Value("${pay.customer-sn}")
    private String certificateSn;

    @Override
    public String sign(String requestBody){
        HttpResponse response = HttpRequest.post(url)
                .header(Header.CONTENT_TYPE, contentType)
                .header("Certificate-SN", certificateSn)
                .header("Accept-Encoding", "*")
                .body(requestBody)
                .execute();
        String sign = null;
        if(response.isOk()){
            String html = response.body();
            Document document = XmlUtil.readXML(html);
            sign =(String) XmlUtil.getByXPath("//html/body/sign", document, XPathConstants.STRING);
        }

//        log.info(response);

        return sign;
    }
}
